package com.gljx.web.controller;

import com.gljx.constant.ActivitiKey;
import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/")
public class SubjectOneRegController {
	
	@Autowired
	private SubjectOneRegService subjectOneRegService;
	
	@Autowired
	private SubjectOneRegentryService subjectOneRegentryService;
	
	//自动注入
	@Autowired
	private DepartmentService departmentService;

	@Autowired
	private CustomLogService customLogService;
	
	@Autowired
	private StudentController studentController;
	
	@Autowired
	private ExamsubscribeService examsubscribeService;

	@Autowired
	private MessageService messageService;

	//导入activiti工具
	ActitiviUtil activitiUtil = new ActitiviUtil();
	
	@RequestMapping(value="/querySubjectOneReg/look.action")
	public String querySubjectOneReg(HttpServletRequest request, @RequestParam(value = "fnumber", defaultValue = "") String fnumber
            , @RequestParam(value = "fdescription", defaultValue = "") String fdescription
            , @RequestParam(value = "cfstudentname", defaultValue = "") String cfstudentname
            , @RequestParam(value = "beginTime", defaultValue = "") String beginTime
            , @RequestParam(value = "endTime", defaultValue = "") String endTime
			, @RequestParam(value = "type",defaultValue = "") String type
			, @RequestParam(value = "selectState",required = false,defaultValue = "-1") String selectState)throws Exception{
		PageBean<SubjectOneReg> pb = new PageBean<>();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        try {           
            fnumber = fnumber.trim();//去空格
            fdescription = fdescription.trim();
            cfstudentname = cfstudentname.trim();
            beginTime=beginTime.trim();
            endTime=endTime.trim();
			if("1".equals(selectState)){//如果传过来的标记为1 所以业务日期为空默认查询全部
				pb = getPageBean(request,user.getFcompanyid(),fnumber,fdescription,cfstudentname,null,null);
			}else{
				//默认时间
				if ("".equals(beginTime) && "".equals(endTime)) {
					beginTime = TimeFormat.getMonth();
					endTime = TimeFormat.getNowTime();
				}
				//获取分页
				pb = getPageBean(request,user.getFcompanyid(),fnumber,fdescription,cfstudentname,beginTime,endTime);
			}
             //计数器
             int i = 0;
             //缓存需要删除的序列
             List<Integer> tem = new ArrayList<>();
           //获取当前分页的值
             List<SubjectOneReg> subjectOneRegList = pb.getBeanList();          
             //把获取到的数据传回页面
             if(cfstudentname.equals("")){
             	cfstudentname=null;
             }
             
           //把获取到的数据传回页面
             for (SubjectOneReg subjectOneReg : subjectOneRegList) {
 				subjectOneReg.setSubjectOneRegentryList(subjectOneRegentryService.selSubjectOneRegByParentId(subjectOneReg.getFid(),cfstudentname));
 				i++;
                //如果子类为空则记住该序列序号
                if (subjectOneReg.getSubjectOneRegentryList().size() ==0) {
                    tem.add(i);
                }
             }             
             //进行集合删除
             for (int j = 0; j < tem.size(); j++) {
             	subjectOneRegList.remove(tem.get(j) - j - 1);
             }
             //生成信息总数
			String messageAmount="共有"+pb.getTr()+"条信息";
            //返回界面的搜索条件
			request.setAttribute("messageAmount",messageAmount);
            request.setAttribute("fnumber", fnumber);
            request.setAttribute("fdescription", fdescription);
            request.setAttribute("cfstudentname", cfstudentname);
            request.setAttribute("beginTime", beginTime);
            request.setAttribute("endTime", endTime);
            request.setAttribute("subjectOneRegList", subjectOneRegList);
            request.setAttribute("pb", pb);
            request.setAttribute("type",type);
			request.setAttribute("selectState",selectState);
		} catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }		
		return "backHome/examManage/subjectOneReg/subjectOneRegList";
	}
	/**
	 * 跳转到增加科一考试登记信息页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/intoAddSubjectOneReg")
	public String intoAddSubjectOneReg(HttpServletRequest request,String type)throws Exception{
		//获取操作人信息
	    User user = (User)request.getSession().getAttribute("user");
	    //获取部门
	    List<Department> departments = departmentService.queryAdminByController(user.getFcompanyid());
	    //获取组织
	    Department department = departmentService.queryAdminByFid(user.getFcompanyid());
	    /*获取当前时间*/
        String createTime = TimeFormat.timeFormat(new Date());
	    //获取上一个编码
		/*String number = subjectOneRegService.selectFnumber(user.getFcompanyid());*/
        //获取编码
		String fnumber = GetFnumber.fnumbers("OR");
        Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
        ca.setTime(new Date()); // 设置时间为当前时间
        ca.add(Calendar.MONTH, -3);// 月份减1
        Date resultDate = ca.getTime(); // 结果
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//业务时间
		String time = sdf.format(new Date());
        String beginTime = sdf.format(resultDate);
        String endTime = sdf.format(new Date());     
		request.setAttribute("beginTime", beginTime);//业务开始时间
        request.setAttribute("endTime", endTime);    //业务结束时间
        request.setAttribute("fnumber", fnumber);//单据编号
        request.setAttribute("department", department);//驾校名
        request.setAttribute("createTime", createTime);//创建时间
        request.setAttribute("user", user);//操作人
        request.setAttribute("type",type);//
        request.setAttribute("time",time);//考试日期
		return"backHome/examManage/subjectOneReg/addSubjectOneReg";
	}
	/**
	 * 增加科目一考试登记信息
	 * @param request
	 * @param subjectOneReg
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/addSubjectOneReg")
	public String addSubjectOneReg(HttpServletRequest request,SubjectOneReg subjectOneReg)throws Exception{
		String [] subfids=request.getParameterValues("subfid");//学员的fid
		String [] subfseq=request.getParameterValues("subfseq");//序列号
		String [] subcfzkzmbh=request.getParameterValues("subcfzkzmbh");//准考证编码
		String [] subfnameL2=request.getParameterValues("subfnameL2");//姓名
		String [] subfnumber=request.getParameterValues("subfnumber");//学员编码
		String [] subcfidcardno=request.getParameterValues("subcfidcardno");//身份证号
		String [] subcfsex=request.getParameterValues("subcfsex");//性别
		for (int i=0;i<subcfsex.length;i++) {
			if(subcfsex[i].equals("男")){
				subcfsex[i]="1";
			}else {
				subcfsex[i]="2";
			}
		}
		String [] subcfsjhm=request.getParameterValues("subcfsjhm");//手机号码
		String [] subcfslzjcxdh=request.getParameterValues("subcfslzjcxdh");//申请准驾车型代号
		String [] subcflocal=request.getParameterValues("subcflocal");//本地异地
		for (int i = 0; i < subcflocal.length; i++) {
			if(subcflocal[i].equals("本地")){
				subcflocal[i]="1";
			}else if(subcflocal[i].equals("异地")){
				subcflocal[i]="2";
			}else{
				subcflocal[i]="3";
			}
		}
		String [] subcflxdh=request.getParameterValues("subcflxdh");//电话
		String [] subcftjrName=request.getParameterValues("subcftjrName");//推荐人姓名
		String [] subcftjrid=request.getParameterValues("subcftjrid");//推荐人id
		String [] subcfkmykss=request.getParameterValues("subcfkmykss");//考试次数
		String [] subcfckbk=request.getParameterValues("subcfckbk");//初考补考
		for (int i = 0; i < subcfckbk.length; i++) {
			if(subcfckbk[i].equals("初考")){
				subcfckbk[i]="1";
			}else{
				subcfckbk[i]="2";
			}
		}
		String [] subcfbxwx=request.getParameterValues("subcfbxwx");//本校外校
		for (int i = 0; i < subcfbxwx.length; i++) {
			if(subcfbxwx[i].equals("本校")){
				subcfbxwx[i]="1";
			}else{
				subcfbxwx[i]="2";
			}
		}
		String [] subcfclazzName=request.getParameterValues("subcfclazzName");//班级
		String [] subcfreceived=request.getParameterValues("subcfreceived");//已收金额
		String [] subcffavorable=request.getParameterValues("subcffavorable");//优惠金额
		String [] subcfamount=request.getParameterValues("subcfamount");//应收金额
		String [] subcfarrearage=request.getParameterValues("subcfarrearage");//欠费金额
		String [] subcfremark=request.getParameterValues("cfremark");//备注
		String [] subcfdajj=request.getParameterValues("subcfdajj");//档案交接
		String [] subcfjnbjj=request.getParameterValues("subcfjnbjj");//技能表交接
		String [] subcfclazzid=request.getParameterValues("subcfclazzid");//班级id
		/*获取uuid*/
        String uuid = GetFid.UUIDIntoFid();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        subjectOneReg.setFid(uuid);
        //公司id
        subjectOneReg.setCfficompanyid(user.getFcompanyid());
        //控制单元id
        subjectOneReg.setFcontrolunitid(user.getFcompanyid());
        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //修改时间
        subjectOneReg.setFcreatetime(createTime);
        //修改人id
        subjectOneReg.setFcreatorid(user.getFid());
        int row =0;
        //添加父类科目一考试登记信息
        row=subjectOneRegService.addSubjectReg(subjectOneReg);
        //添加子类
        for (int i=0;i<subfids.length;i++) {
			SubjectOneRegentry subjectOneRegentry=new SubjectOneRegentry();
			subjectOneRegentry.setFseq(Long.valueOf(subfseq[i]));
			subjectOneRegentry.setFid(GetFid.UUIDIntoFid());
			subjectOneRegentry.setFparentid(subjectOneReg.getFid());
			subjectOneRegentry.setCfzkzmbh(subcfzkzmbh[i]);
			subjectOneRegentry.setCfstudentid(subfids[i]);
			subjectOneRegentry.setCfstudentname(subfnumber[i]);
			subjectOneRegentry.setStudentName(subfnameL2[i]);
			subjectOneRegentry.setCfidcardno(subcfidcardno[i]);
			subjectOneRegentry.setCfsex(Long.valueOf(subcfsex[i]));
			subjectOneRegentry.setCfmobile(subcfsjhm[i]);
			subjectOneRegentry.setCfbdyd(Long.valueOf(subcflocal[i]));
			subjectOneRegentry.setCfsqzjcxdh(subcfslzjcxdh[i]);
			subjectOneRegentry.setCfphone(subcflxdh[i]);
			subjectOneRegentry.setCftjr(subcftjrName[i]);
			subjectOneRegentry.setCfkscs(Long.valueOf(subcfkmykss[i]));
			subjectOneRegentry.setCfckbk(subcfckbk[i]);
			subjectOneRegentry.setCfbxwx(subcfbxwx[i]);
			subjectOneRegentry.setCfclazz(subcfclazzName[i]);
			subjectOneRegentry.setCfysje(new BigDecimal(subcfreceived[i]));
			subjectOneRegentry.setCfyhje(new BigDecimal(subcffavorable[i]));
			subjectOneRegentry.setCfyisje(new BigDecimal(subcfamount[i]));
			subjectOneRegentry.setCfqfje(new BigDecimal(subcfarrearage[i]));
			subjectOneRegentry.setCfremark(subcfremark[i]);			
			row += subjectOneRegentryService.addSubjectOneRegentry(subjectOneRegentry);
			//添加学员的服务日志
			customLogService.addLog("考试管理",
					"新增了学员:"+subjectOneRegentry.getCfstudentname()+subjectOneRegentry.getStudentName()+",科目一考试登记!申请车型:"+subjectOneRegentry.getCfsqzjcxdh()
					+",考试日期:"+subjectOneReg.getFbizdate()+",单据编号:"+subjectOneReg.getFnumber(),
					subjectOneRegentry.getCfstudentid(), user.getFid());
		}
		String result = "0";
		if(row == subfids.length+1){
			result = "1";
		}
        //添加日志
        customLogService.addLog("考试管理", TimeFormat.timeFormat(new Date()) + "科目一考试登记进行增加", null, user.getFid());
		return "redirect:/DrivingSys/intoUpdateSubjectOneReg?type="+result+"&fid="+uuid;
	}
	/**
	 * 跳转到科目一考试登记修改页面
	 * @param request
	 * @param fid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/intoUpdateSubjectOneReg")
	public String intoUpdateSubjectOneReg(HttpServletRequest request,
			@RequestParam(value="fid",required=false) String fid)throws Exception{
		//获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //获取组织
	    Department department = departmentService.queryAdminByFid(user.getFcompanyid());
        //获取父类科目一考合格登记信息
        SubjectOneReg subjectOneReg =subjectOneRegService.selectSubjectOneRegByFid(fid);
        if(subjectOneReg == null){
			return "/error/not_data";//单据不存在则跳转到错误页面
		}
        //获取子类信息
        subjectOneReg.setSubjectOneRegentryList(subjectOneRegentryService.selSubjectOneRegByParentId(fid,null));
        //获取当前时间
	    Calendar now = Calendar.getInstance();
	   	now.add(Calendar.MONTH, -3);// 月份减1
	    /*获取当前时间*/
        Date resultDate = now.getTime(); // 结果
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String beginTime = sdf.format(resultDate);
        String endTime = sdf.format(new Date());
        //根据fid查找科目一考试登记信息
		SubjectOneReg _subjectOneReg =subjectOneRegService.selectSubjectOneRegByFid(fid);
		/*//查询该单据是否之前有提交过的流程历史记录
		String result = activitiUtil.getTaskStateByUser(
				ActivitiKey.SUBJECTONEREG_KEY,
				_subjectOneReg.getFnumber()                  //单据
		);
		if(activitiUtil.notTask.equals(result))
		{
			System.out.println("该单据没有对应流程");        //没有历史流程（从来没有过流程的“新单据”）
			request.setAttribute("historyActiviti","no");
		}
		else if(activitiUtil.FINISH.equals(result))
		{
			System.out.println("流程已结束");                //只有有历史流程
			request.setAttribute("historyActiviti","yes");
		}//剩下两种是该任务进行中
		else if(activitiUtil.notAssign.equals(result))
		{
			System.out.println("经办人不匹配");               //正在进行的流程，但是经办人跟当前用户不匹配
			request.setAttribute("historyActiviti","yes");
		}
		else if(activitiUtil.ISPOWER.equals(result))
		{
			System.out.println("当前用户可以审核该单据");
			request.setAttribute("historyActiviti","yes");
		*//**正在进行的流程，且当前用户能够审核
		 * 如果是进入可提交的详情页面，这个标记表示
		 * 此流程进行中，即用户点击提交只需推进流程即可
		 *//*
		}*/
		request.setAttribute("activitiState",subjectOneRegService.selectAuditPerson(user,_subjectOneReg.getFnumber()));
		request.setAttribute("activitiBPMN_KEY",ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.SUBJECTONEREG_KEY_GL : ActivitiKey.SUBJECTONEREG_KEY_NC);
		request.setAttribute("beginTime", beginTime);
        request.setAttribute("endTime", endTime);      
        request.setAttribute("subjectOneReg", subjectOneReg);
		request.setAttribute("department",department);
		return "backHome/examManage/subjectOneReg/updateSubjectOneReg";
	}
	@RequestMapping(value="/updateSubjectOneReg")
	public String updateSubjectOneReg(HttpServletRequest request,SubjectOneReg subjectOneReg,String type)throws Exception{
		String [] subfids=request.getParameterValues("subfid");//fid
		String [] subfseq=request.getParameterValues("subfseq");//序列号
		String [] subcfzkzmbh=request.getParameterValues("subcfzkzmbh");//准考证编码
		String [] subfnameL2=request.getParameterValues("subfnameL2");//姓名
		String [] subfnumber=request.getParameterValues("subfnumber");//学员编码
		String [] subcfidcardno=request.getParameterValues("subcfidcardno");//身份证号
		String [] subcfsex=request.getParameterValues("subcfsex");//性别
		for (int i=0;i<subcfsex.length;i++) {
			if(subcfsex[i].equals("男")){
				subcfsex[i]="1";
			}else {
				subcfsex[i]="2";
			}
		}
		String [] subcfsjhm=request.getParameterValues("subcfsjhm");//手机号码
		String [] subcfslzjcxdh=request.getParameterValues("subcfslzjcxdh");//申请准驾车型代号
		String [] subcflocal=request.getParameterValues("subcflocal");//本地异地
		for (int i = 0; i < subcflocal.length; i++) {
			if(subcflocal[i].equals("本地")){
				subcflocal[i]="1";
			}else if(subcflocal[i].equals("异地")){
				subcflocal[i]="2";
			}else{
				subcflocal[i]="3";
			}
		}
		String [] subcflxdh=request.getParameterValues("subcflxdh");//电话
		String [] subcftjrName=request.getParameterValues("subcftjrName");//推荐人姓名
		String [] subcftjrid=request.getParameterValues("subcftjrid");//推荐人id
		String [] subcfkmykss=request.getParameterValues("subcfkmykss");//考试次数
		String [] subcfckbk=request.getParameterValues("subcfckbk");//初考补考
		for (int i = 0; i < subcfckbk.length; i++) {
			if(subcfckbk[i].equals("初考")){
				subcfckbk[i]="1";
			}else{
				subcfckbk[i]="2";
			}
		}
		String [] subcfbxwx=request.getParameterValues("subcfbxwx");//本校外校
		for (int i = 0; i < subcfbxwx.length; i++) {
			if(subcfbxwx[i].equals("本校")){
				subcfbxwx[i]="1";
			}else{
				subcfbxwx[i]="2";
			}
		}
		String [] subcfclazzName=request.getParameterValues("subcfclazzName");//班级
		String [] subcfreceived=request.getParameterValues("subcfreceived");//已收金额
		String [] subcffavorable=request.getParameterValues("subcffavorable");//优惠金额
		String [] subcfamount=request.getParameterValues("subcfamount");//应收金额
		String [] subcfarrearage=request.getParameterValues("subcfarrearage");//欠费金额
		String [] subcfremark=request.getParameterValues("cfremark");//备注
		String [] subcfdajj=request.getParameterValues("subcfdajj");//档案交接
		String [] subcfjnbjj=request.getParameterValues("subcfjnbjj");//技能表交接
		String [] subcfclazzid=request.getParameterValues("subcfclazzid");//班级id
		//获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
		 //获取当前修改时间
        String updateTime = TimeFormat.timeFormat(new Date());
       /* if (subjectOneReg.getCfbillstate()==5L) {//如何状态为5则是审计
        	subjectOneReg.setFauditorid(user.getFid());//设置审计人id
			type = "3";
        }else{
			type = "2";
		}*/
        //把创建时间和业务日期清空不让修改
        subjectOneReg.setFcreatetime(null);
        subjectOneReg.setFlastupdateuserid(user.getFid());
        subjectOneReg.setFlastupdatetime(updateTime);
		//修改父类
        int row1 = subjectOneRegService.updateSubjectOneRegByFid(subjectOneReg);
        //删除父类的子类
        subjectOneRegentryService.deleteByParentId(subjectOneReg.getFid(),null,null,null);
        //添加子类
		int row2=0;
        for (int i=0;i<subfids.length;i++) {
			SubjectOneRegentry subjectOneRegentry=new SubjectOneRegentry();
			subjectOneRegentry.setFseq(Long.valueOf(subfseq[i]));
			subjectOneRegentry.setFid(GetFid.UUIDIntoFid()+i);
			subjectOneRegentry.setFparentid(subjectOneReg.getFid());
			subjectOneRegentry.setCfzkzmbh(subcfzkzmbh[i]);		
			subjectOneRegentry.setCfstudentid(subfids[i]);
			subjectOneRegentry.setCfstudentname(subfnumber[i]);
			subjectOneRegentry.setStudentName(subfnameL2[i]);
			subjectOneRegentry.setCfidcardno(subcfidcardno[i]);
			subjectOneRegentry.setCfsex(Long.valueOf(subcfsex[i]));
			subjectOneRegentry.setCfmobile(subcfsjhm[i]);
			subjectOneRegentry.setCfbdyd(Long.valueOf(subcflocal[i]));
			subjectOneRegentry.setCfsqzjcxdh(subcfslzjcxdh[i]);
			subjectOneRegentry.setCfphone(subcflxdh[i]);
			subjectOneRegentry.setCftjr(subcftjrName[i]);
			subjectOneRegentry.setCfkscs(Long.valueOf(subcfkmykss[i]));
			subjectOneRegentry.setCfckbk(subcfckbk[i]);
			subjectOneRegentry.setCfbxwx(subcfbxwx[i]);
			subjectOneRegentry.setCfclazz(subcfclazzName[i]);
			subjectOneRegentry.setCfysje(new BigDecimal(subcfreceived[i]));
			subjectOneRegentry.setCfyhje(new BigDecimal(subcffavorable[i]));
			subjectOneRegentry.setCfyisje(new BigDecimal(subcfamount[i]));
			subjectOneRegentry.setCfqfje(new BigDecimal(subcfarrearage[i]));
			subjectOneRegentry.setCfremark(subcfremark[i]);
			row2 += subjectOneRegentryService.addSubjectOneRegentry(subjectOneRegentry);
			//添加学员的服务日志
			customLogService.addLog("考试管理",
					"修改了学员:"+subjectOneRegentry.getCfstudentname()+subjectOneRegentry.getStudentName()+",科目一考试登记!申请车型:"+subjectOneRegentry.getCfsqzjcxdh()
							+",考试日期:"+subjectOneReg.getFbizdate()+",单据编号:"+subjectOneReg.getFnumber(),
					subjectOneRegentry.getCfstudentid(), user.getFid());
		}
		String result="";
        if(row1 >0 && row2 >0){
        	result ="1";
		}
        //添加日志
        customLogService.addLog("考试管理", TimeFormat.timeFormat(new Date()) + "科目一考试登记进行修改", null, user.getFid());
		return "redirect:/DrivingSys/querySubjectOneReg/look.action?type="+result+"";
	}
	/**
	 * 根据fid删除科目一考试信息
	 * @param request
	 * @param deleteId
	 * @param fid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteSubjectOneRegByFid")
	public String deleteSubjectOneRegByFid(HttpServletRequest request, String[] deleteId,String fid)throws Exception{
		User user = (User) request.getSession().getAttribute("user");
        //删除记录
		if(fid==null || fid.equals("")){
			for (int i = 0; i < deleteId.length; i++) {
	            /*过滤为空的删除操作*/
	            if (!deleteId[i].equals("")&&deleteId[i]!=null) {
	            	SubjectOneReg subjectOneReg =subjectOneRegService.selectSubjectOneRegByFid(deleteId[i]);
	            	//删除历史流程或者正在进行的流程
					/*activitiUtil.deleteTask(ActivitiKey.SUBJECTONEREG_KEY_GL,subjectOneReg.getFnumber());*/
					activitiUtil.deleteTask(
							ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.SUBJECTONEREG_KEY_GL : ActivitiKey.SUBJECTONEREG_KEY_NC,
							subjectOneReg.getFnumber());
	            	subjectOneRegService.deleteByPrimaryKey(deleteId[i]);//删除父类
	            	subjectOneRegentryService.deleteByParentId(deleteId[i],user,subjectOneReg.getFbizdate(),(String) subjectOneReg.getFnumber());//删除子类
	            }
	        }	
		}else{
			SubjectOneReg subjectOneReg =subjectOneRegService.selectSubjectOneRegByFid(fid);
			//删除历史流程或者正在进行的流程
			activitiUtil.deleteTask(ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.SUBJECTONEREG_KEY_GL : ActivitiKey.SUBJECTONEREG_KEY_NC,subjectOneReg.getFnumber());
			subjectOneRegService.deleteByPrimaryKey(fid);//删除父类
			subjectOneRegentryService.deleteByParentId(fid,user,subjectOneReg.getFbizdate(),(String)subjectOneReg.getFnumber());//删除子类
        }
		//添加日志
        customLogService.addLog("考试管理", TimeFormat.timeFormat(new Date()) + "科目一考试登记进行删除", null, user.getFid());
		return "redirect:/DrivingSys/querySubjectOneReg/look.action";
	}
	/**
	 * 跟据业务日期查找科目一预约成功的学员
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/selExamsubscribeByFbizdate")
	public Object selExamsubscribeByFbizdate(HttpServletRequest request,String fbizdate,String carType)throws Exception{
		User user = (User) request.getSession().getAttribute("user");
		List<Examsubscribe> examsubscribeList=null;
		examsubscribeList=examsubscribeService.selExamsubcribeByFbizdate(user.getFcompanyid(),"2",fbizdate,carType);
		//做去重操作防止出現同一天多条单据出现同一個学员有
		for (int i = 0; i < examsubscribeList.size() ; i++) {
			for (int j = examsubscribeList.size()-1; j > i ; j--) {
				if(examsubscribeList.get(i).getCfstudentid().equals(examsubscribeList.get(j).getCfstudentid())){//如果学员的fid相同则删除一个
					examsubscribeList.remove(j);
				}
			}
		}
		return examsubscribeList;
	}

	/**
	 *  提交科目一考试登记单据到activiti
	 * @throws Exception
	 */
	@RequestMapping(value = "submitSubjectOneRegActiviti" )
	@ResponseBody
	public Object submitSubjectOneRegActiviti(HttpServletRequest request,String fnumber,String fid)throws Exception{
		//获取父类科目一考合格登记信息
		SubjectOneReg _subjectOneReg =subjectOneRegService.selectSubjectOneRegByFid(fid);
		//根据父类id查找子类
		List<SubjectOneRegentry>  subjectOneRegentries= subjectOneRegentryService.selSubjectOneRegByParentId(fid,null);
		User user = (User) request.getSession().getAttribute("user");
		String result = "";
		//2.将这个单据编号和你需要保存的流程变量存入map集合中
		Map<String,Object> map = new HashMap<String,Object>();
		if(fnumber != null || !"".equals(fnumber)){
			map.put(ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.SUBJECTONEREG_KEY_GL : ActivitiKey.SUBJECTONEREG_KEY_NC,fnumber);
		}else{
			result ="failed";
		}

		//提交之前先判断该单据是否之前有流程历史记录
		String historyRecord =activitiUtil.getTaskStateByUser(
				ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.SUBJECTONEREG_KEY_GL : ActivitiKey.SUBJECTONEREG_KEY_NC,
				fnumber);
		if(historyRecord.equals("notAssign") || historyRecord.equals("power")){//如果之前有流程就不需要提交
			System.out.println("之前有正在进行的流行实例!");
			//只需要推进流程即可
			Message message1=activitiUtil.complteFlowByVariable(
					ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.SUBJECTONEREG_KEY_GL : ActivitiKey.SUBJECTONEREG_KEY_NC,  //指定要启动的流程定义
					fnumber                     //流程变量
			);
			if(message1 !=null){
				message1.setMessage("科目一考试登记 审核 #"+fnumber+"# ");//消息内容
				message1.setUrl("/intoUpdateSubjectOneReg?fid="+fid);//详细路径
				message1.setEditUrl("/checkSubjectOneRegActiviti?fid=" + fid+"&fnumber=" + fnumber);
				messageService.insert(message1);
			}
		}else{//否则作提交操作
			//3.调用方法
			String piID = activitiUtil.creatFlow(
					ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.SUBJECTONEREG_KEY_GL : ActivitiKey.SUBJECTONEREG_KEY_NC,  //指定要启动的流程定义
					map                     //流程变量
			);
			Message message2=activitiUtil.completeFlowByPiID(piID);
			if(message2 !=null){
				message2.setMessage("科目一考试登记 审核 #"+fnumber+"# ");//消息内容
				message2.setUrl("/intoUpdateSubjectOneReg?fid="+fid);//详细路径
				message2.setEditUrl("/checkSubjectOneRegActiviti?fid=" + fid+"&fnumber=" + fnumber);
				messageService.insert(message2);
			}
		}
		SubjectOneReg subjectOneReg =new SubjectOneReg();
		subjectOneReg.setFnumber(fnumber);
		subjectOneReg.setFid(fid);
		subjectOneReg.setCfbillstate(4L);//提交状态
		//修改
		int row =subjectOneRegService.updateSubjectOneRegByFid(subjectOneReg);
		if(subjectOneRegentries !=null){
			for (int i = 0; i < subjectOneRegentries.size(); i++) {
				//添加学员的服务日志
				customLogService.addLog("考试管理",
						 "提交了学员:"+subjectOneRegentries.get(i).getCfstudentname()+subjectOneRegentries.get(i).getStudentName()+",科目一考试登记!申请车型:"+subjectOneRegentries.get(i).getCfsqzjcxdh()
								+",考试日期:"+_subjectOneReg.getFbizdate()+",单据编号:"+_subjectOneReg.getFnumber(),
						subjectOneRegentries.get(i).getCfstudentid(), user.getFid());
			}
		}
		if(row > 0){
			result= "success";
		}
		Map<String,String> _map =new HashMap<>();
		_map.put("result",result);
		return _map;
	}

	/**
	 * 审核activiti里面的单据
	 * @param fid
	 * @param fnumber
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "checkSubjectOneRegActiviti")
	@ResponseBody
	public Object checkSubjectOneRegActiviti(HttpServletRequest request,String fid,String fnumber,@RequestParam(defaultValue = "1", value = "agree")String agree,String auditcomment) throws Exception{
		//获取当前登录用户的信息
		User user =(User)request.getSession().getAttribute("user");
		String result = "failed";
		Integer agreesate=null;
		if(agree != null || !"".equals(agree)){
			agreesate=Integer.parseInt(agree);
		}
		//2.1审核有两种情况同意与不同意，不同意可能有批注
		String message = auditcomment;
		Object returnMsg =
				activitiUtil
						.auditComplteMessage(//新的方法，自定义流程不需要这个
								ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.SUBJECTONEREG_KEY_GL : ActivitiKey.SUBJECTONEREG_KEY_NC,
								fnumber,                  //单据
								agreesate,                 //1、0是否同意取决于你的流程图
								message              //批注，直接把前端传过来的string塞进来
						);
		SubjectOneReg subjectOneReg =new SubjectOneReg();
		subjectOneReg.setFnumber(fnumber);
		subjectOneReg.setFid(fid);
		//subjectOneReg.setFauditorid(user.getFid());//设置审计人id
		if(returnMsg instanceof Message){
			Message resultMsg = (Message) returnMsg;
			resultMsg.setMessage("科目一考试登记-审核 #"+fnumber+"# ");//消息内容
			resultMsg.setUrl("/intoUpdateSubjectOneReg?fid="+fid);//详细路径
			resultMsg.setEditUrl("/checkSubjectOneRegActiviti?fid=" + fid+"&fnumber=" + fnumber);

			messageService.insert(resultMsg);
			//获取父类科目一考合格登记信息
			SubjectOneReg _subjectOneReg =subjectOneRegService.selectSubjectOneRegByFid(fid);
			//根据父类id查找子类
			List<SubjectOneRegentry>  subjectOneRegentries= subjectOneRegentryService.selSubjectOneRegByParentId(fid,null);
			if(subjectOneRegentries !=null){
				for (int i = 0; i < subjectOneRegentries.size(); i++) {
					//添加学员的服务日志
					customLogService.addLog("考试管理",
							  "审核了学员:"+subjectOneRegentries.get(i).getCfstudentname()+subjectOneRegentries.get(i).getStudentName()+",科目一考试登记!申请车型:"+subjectOneRegentries.get(i).getCfsqzjcxdh()
									+",考试日期:"+_subjectOneReg.getFbizdate()+",单据编号:"+_subjectOneReg.getFnumber(),
							subjectOneRegentries.get(i).getCfstudentid(), user.getFid());
				}

			}
			result= "success";
		}else if(activitiUtil.notAssign .equals(returnMsg)) {
			System.out.println("当前用户不是要求的经办人");
			result="isNoResponsiblePerson";
		}
		else if(activitiUtil.FINISH.equals(returnMsg)) {
			System.out.println("此流程成功推进，并且此流程已经结束");
			subjectOneReg.setFauditorid(user.getFid());//设置审计人id
			subjectOneReg.setCfbillstate(5L);//审核状态
			//修改
			int row =subjectOneRegService.updateSubjectOneRegByFid(subjectOneReg);
			if(row >0){
				result= "successAndOver";
			}
		}
		else if(activitiUtil.SUCCESS.equals(returnMsg)) {
			System.out.println("此流程成功推进");
			result= "success";
		}
		else if(activitiUtil.notTask.equals(returnMsg)) {
			System.out.println("没有找到正在进行的相关流程");
		}
		if(agree.equals("2")){
			subjectOneReg.setCfbillstate(3L);//保存状态
			//修改
			subjectOneRegService.updateSubjectOneRegByFid(subjectOneReg);
		}
		Map<String,String> _map =new HashMap<>();
		_map.put("result",result);
		return _map;
	}

	/**
	 * 反审核科目一单据
	 * @param request
	 * @param fid
	 * @param againstAuditcomment
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "againstCheckSubjectOneRegActiviti")
	@ResponseBody
	public Object againstCheckSubjectOneRegActiviti(HttpServletRequest request,String fid,String fnumber,String againstAuditcomment ,String activitiState)throws  Exception{
		//获取当前登录用户的信息
		User user =(User)request.getSession().getAttribute("user");
		String result ="falied";
		if("1".equals(activitiState)){//当前有正在进行的流程
			Object _result = activitiUtil.jumpActivtiMessage(
					ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.SUBJECTONEREG_KEY_GL : ActivitiKey.SUBJECTONEREG_KEY_NC,
					fnumber,                  //单据
					againstAuditcomment
			);
			if(_result instanceof Message){
				Message resultMsg = (Message) _result;
				resultMsg.setMessage("科目一考试登记-反审核 #"+fnumber+"#");//消息内容
				resultMsg.setUrl("/intoUpdateSubjectOneReg?fid="+fid);//详细路径
				resultMsg.setEditUrl("/checkSubjectOneRegActiviti?fid=" + fid+"&fnumber=" + fnumber);

				messageService.insert(resultMsg);
			}
			else if(activitiUtil.SUCCESS.equals(_result))
			{	//获取父类科目一考合格登记信息
				SubjectOneReg _subjectOneReg =subjectOneRegService.selectSubjectOneRegByFid(fid);
				//根据父类id查找子类
				List<SubjectOneRegentry>  subjectOneRegentries= subjectOneRegentryService.selSubjectOneRegByParentId(fid,null);
				if(subjectOneRegentries !=null){
					for (int i = 0; i < subjectOneRegentries.size(); i++) {
						//添加学员的服务日志
						customLogService.addLog("考试管理",
								"反审核了学员:"+subjectOneRegentries.get(i).getCfstudentname()+subjectOneRegentries.get(i).getStudentName()+",科目一考试登记!申请车型:"+subjectOneRegentries.get(i).getCfsqzjcxdh()
										+",考试日期:"+_subjectOneReg.getFbizdate()+",单据编号:"+_subjectOneReg.getFnumber(),
								subjectOneRegentries.get(i).getCfstudentid(), user.getFid());
					}
				}
				System.out.println("成功!");
			}else if(activitiUtil.notActiviti.equals(result))
			{
				System.out.println("找不到流程节点");

			}else if(activitiUtil.notTask.equals(result))
			{
				System.out.println("没有找到任务");
			}
		}else{//当前没有进行的流程
			//直接修改单据状态为“保存”状态
			Message message2 = activitiUtil.getMessage(
					ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.SUBJECTONEREG_KEY_GL : ActivitiKey.SUBJECTONEREG_KEY_NC,
					fnumber                  //单据
			);

			if(message2 != null)
			{
				message2.setMessage("科目一考试登记-审核 #"+fnumber+"#");//消息内容
				message2.setUrl("/intoUpdateSubjectOneReg?fid="+fid);//详细路径
				message2.setEditUrl("/checkSubjectOneRegActiviti?fid=" + fid+"&fnumber=" + fnumber);

				messageService.insert(message2);
			}
		}
		//将单据状态修改成保存状态3
		SubjectOneReg subjectOneReg = new SubjectOneReg();
		subjectOneReg.setFid(fid);
		subjectOneReg.setCfbillstate(3L);//保存状态
		subjectOneReg.setFauditorid(user.getFid());//设置反审计人id
		int row = subjectOneRegService.updateSubjectOneRegByFid(subjectOneReg);
		if (row > 0) {
			result = "success";
		}
		Map<String,String> _map =new HashMap<>();
		_map.put("result",result);
		return _map;
	}
	
	@SuppressWarnings("unchecked")
    /**
     * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
     * @return 返回PageBean实体类
     * @throws Exception
     */
    public PageBean<SubjectOneReg> getPageBean(HttpServletRequest request, String companyId, String fnumber,
            String fdescription,String studentName,String beginTime, String endTime) throws Exception {

        int offset;//从第几条数据开始加载
        if (request.getParameter("pager.offset") == null) {
            offset = 0;
        } else {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        //拼接SQL语句
        StringBuffer psql = new StringBuffer();       
        psql.append(" SELECT distinct S.FID,S.FCREATORID,S.FCREATETIME,S.FLASTUPDATEUSERID,S.FLASTUPDATETIME,S.FCONTROLUNITID, "+
        				"S.FNUMBER,to_char(S.FBIZDATE,'YYYY-MM-DD') FBIZDATE ,S.FHANDLERID,S.FDESCRIPTION,S.FAUDITORID,S.CFFICOMPANYID,S.CFBILLSTATE, "+
        				"S.CFCARTYPE,S.CFZBS,S.CFDQBKRS, E.NAME AS checkName,U.NAME AS createName "+
        				"FROM CT_DS_SUBJECTONEREG S  LEFT JOIN T_E_USER U ON U.FID=S.FCREATORID LEFT JOIN T_E_USER E ON E.FID=S.FAUDITORID "+
        				" LEFT JOIN CT_DS_SUBJECTONEREGENTRY S1 ON S1.FPARENTID = S.FID"+
        				" LEFT JOIN CT_DS_STUDENT STU ON STU.FID = S1.CFSTUDENTID "+
        				" WHERE S.FCONTROLUNITID='"+companyId+"'");
       
        if (fnumber == null || fnumber.equals("")) {
			
		} else {
			psql.append( "AND S.FNUMBER LIKE '%" + fnumber + "%' ");
		}
		if (fdescription == null || fdescription.equals("")) {

		} else {
			psql.append( "AND S.FDESCRIPTION LIKE '%" + fdescription + "%'");
		}
		if (studentName == null || studentName.equals("")) {

		} else {
			psql.append( "AND STU.FNAME_L2 LIKE '%" + studentName + "%'");
		}
		if (beginTime == null || endTime == null) {
		/*	 beginTime = TimeFormat.getMonth();
		} else if(endTime == null || endTime.equals("")){				 	
		        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");			      
		        endTime = sdf.format(new Date());
			psql.append("AND TO_CHAR(S.FBIZDATE,'yyyy-MM-dd') BETWEEN '" + beginTime + "' AND '" + endTime + "'"); */
		}else{
			psql.append("AND TO_CHAR(S.FBIZDATE,'yyyy-MM-dd') BETWEEN '" + beginTime + "' AND '" + endTime + "'"); 
		}
		
		//psql.append(" ORDER BY to_char(S.FBIZDATE,'YYYY-MM-DD') DESC");
		
		psql.append(" ORDER BY FBIZDATE DESC");
		//System.out.println(psql);
        int psize = 50; //每页显示数
        int pindex = offset / psize;//+1  页码从0开始
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = subjectOneRegService.selectPage(pindex, psql.toString(), psize);
        PageBean<SubjectOneReg> pb = new PageBean<>();
        pb.setPc(pindex); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql.toString()); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        pb.setBeanList((List<SubjectOneReg>) paramMap.get("v_cur")); //每页数据集
        return pb;
    }
	
	/**
	 * 取记录总数 dmz 20160921
	 * @param psql  SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception{
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap=subjectOneRegService.selectPageCount(psql);
		return paramMap;
	}

	/**
	 * 查询科目一考试登记 导出excel
	 * @param response
	 * @param request
	 * @param fnumber
	 * @param fdescription
	 * @param studentName
	 * @param beginTime
	 * @param endTime
	 */
	@RequestMapping(value = "/importSubjectOneReg")
	public void importSubjectOneReg(HttpServletResponse response, HttpServletRequest request
			, @RequestParam(value = "fnumber", defaultValue = "") String fnumber
			, @RequestParam(value = "fdescription", defaultValue = "") String fdescription
			, @RequestParam(value = "studentName", defaultValue = "") String studentName
			, @RequestParam(value = "beginTime", defaultValue = "") String beginTime
			, @RequestParam(value = "endTime", defaultValue = "") String endTime){

		if("".equals(studentName)){
			studentName =null;
		}
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//定义接收类型
		List<Object> data = new ArrayList<>();
		//查询数据
		List<SubjectOneReg> subjectOneRegs =subjectOneRegService.selectSubjectOneReg(user.getFcompanyid(),fnumber,fdescription,beginTime,endTime);
		for (SubjectOneReg subjectOneReg :subjectOneRegs){
			subjectOneReg.setSubjectOneRegentryList(subjectOneRegentryService.selSubjectOneRegByParentId(subjectOneReg.getFid(),studentName));
			for (int i = 0; i <subjectOneReg.getSubjectOneRegentryList().size() ; i++) {
				data.add(subjectOneReg.getFnumber());
				data.add(subjectOneReg.getFbizdate());
				data.add(subjectOneReg.getFdescription());
				if(subjectOneReg.getCfbillstate() == 3L){
					data.add("保存");
				}else if(subjectOneReg.getCfbillstate() == 4L){
					data.add("提交");
				}else{
					data.add("审核");
				}
				data.add(subjectOneReg.getCheckName());
				data.add(subjectOneReg.getCreateName());
				data.add(subjectOneReg.getCfcartype());
				data.add(subjectOneReg.getCfzbs());
				data.add(subjectOneReg.getCfdqbkrs());
				data.add(subjectOneReg.getSubjectOneRegentryList().get(i).getCfzkzmbh());
				data.add(subjectOneReg.getSubjectOneRegentryList().get(i).getStudentName());
				data.add(subjectOneReg.getSubjectOneRegentryList().get(i).getCfstudentname());
				data.add(subjectOneReg.getSubjectOneRegentryList().get(i).getCfidcardno());
				if(subjectOneReg.getSubjectOneRegentryList().get(i).getCfsex() == 1L){
					data.add("男");
				}else if(subjectOneReg.getSubjectOneRegentryList().get(i).getCfsex() == 2L){
					data.add("女");
				}else{
					data.add("");
				}
				data.add(subjectOneReg.getSubjectOneRegentryList().get(i).getCfmobile());
				data.add(subjectOneReg.getSubjectOneRegentryList().get(i).getCfsqzjcxdh());
				if(subjectOneReg.getSubjectOneRegentryList().get(i).getCfbdyd() == 1L){
					data.add("本地");
				}else if(subjectOneReg.getSubjectOneRegentryList().get(i).getCfbdyd() == 2L){
					data.add("异地");
				}else if(subjectOneReg.getSubjectOneRegentryList().get(i).getCfbdyd() == 3L){
					data.add("学生");
				}else{
					data.add("");
				}
				data.add(subjectOneReg.getSubjectOneRegentryList().get(i).getCfphone());
				data.add(subjectOneReg.getSubjectOneRegentryList().get(i).getCftjr());
				data.add(subjectOneReg.getSubjectOneRegentryList().get(i).getCfkscs());
				if("1".equals(subjectOneReg.getSubjectOneRegentryList().get(i).getCfckbk())){
					data.add("初考");
				}else if("2".equals(subjectOneReg.getSubjectOneRegentryList().get(i).getCfckbk())){
					data.add("补考");
				}else{
					data.add("");
				}
				if("1".equals(subjectOneReg.getSubjectOneRegentryList().get(i).getCfbxwx())){
					data.add("本校");
				}else if("2".equals(subjectOneReg.getSubjectOneRegentryList().get(i).getCfbxwx())){
					data.add("外校");
				}else{
					data.add("");
				}
				data.add(subjectOneReg.getSubjectOneRegentryList().get(i).getCfclazz());
				data.add(subjectOneReg.getSubjectOneRegentryList().get(i).getCfyisje());
				data.add(subjectOneReg.getSubjectOneRegentryList().get(i).getCfyhje());
				data.add(subjectOneReg.getSubjectOneRegentryList().get(i).getCfysje());
				data.add(subjectOneReg.getSubjectOneRegentryList().get(i).getCfqfje());
				data.add(subjectOneReg.getSubjectOneRegentryList().get(i).getCfremark());
				if(subjectOneReg.getSubjectOneRegentryList().get(i).getCfjnbjj() != null){
					if(subjectOneReg.getSubjectOneRegentryList().get(i).getCfjnbjj() == 0L){
						data.add("否");
					}else {
						data.add("是");
					}
				}else{
					data.add(null);
				}
				if(subjectOneReg.getSubjectOneRegentryList().get(i).getCfdajj() != null){
					if(subjectOneReg.getSubjectOneRegentryList().get(i).getCfdajj() == 0L){
						data.add("否");
					}else{
						data.add("是");
					}
				}else{
					data.add(null);
				}
			}
		}
		//头部数据
		String head[] = {"单据编号", "业务日期", "参考信息", "单据状态","审核人名称", "制单人名称",  "车型", "指标数","当前报考人数","准考证名编号",
				"学员姓名","学员编码","身份证号码","性别","手机号码","申请准驾车型代号","本地/异地","电话","推荐人","考试次数"
				,"初考/补考","本校/外校","班级","已收","优惠","应收","欠费","备注","技能表交接","档案交接"};
		//长度
		Integer length[] = {9000, 5000, 5000, 3000, 3000, 3000, 3000, 3000,3000,5000,
							3000,5000,9000,3000,3000,3000,3000,3000,3000,3000,
							3000,3000,5000,3000,3000,3000,3000,5000,3000,3000};
		try {
			//导出Excel
			CommonExport.importExcel(response, "科目一考试登记" + TimeFormat.getNowTime2() + ".xls", "科目一考试登记", data, head, length);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
